 /*
 * Written by Anders Fongen
 * Norwegian Defence Research Establishment (FFI)
 * Email: anders@fongen.no
 */

package no.ffi.gismoidm.idp;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author anf
 * Created on 09.sep.2009
 */
public class AttributeDAO {

    String dbUrl,driverClass,sqlStmt,user,password;
    Connection conn;
    PreparedStatement stmt;
    
    public AttributeDAO() throws Exception {
        Config.loadPropertiesFrom(null);
        dbUrl = Config.getProperty("DB_URL");
        driverClass = Config.getProperty("DB_DRIVERCLASS");
        sqlStmt = Config.getProperty("DB_SQLSTMT");
        user = Config.getProperty("DB_USER");
        password = Config.getProperty("DB_PASSWORD");

        Class.forName(driverClass);
        if (user==null || user.trim().equals(""))
            conn = DriverManager.getConnection(dbUrl);
        else
            conn = DriverManager.getConnection(dbUrl, user, password);
        stmt = conn.prepareStatement(sqlStmt);
    }

    public List getAttributesFor(String subject) throws Exception {
        if (subject==null) return null;
        stmt.setString(1, subject.toUpperCase()); 
        ResultSet rs = stmt.executeQuery();
        ArrayList attrList = new ArrayList();
        while (rs.next()) {
            String attrName = rs.getString(2);
            String attrValue = rs.getString(3);
            if (attrName==null) continue;
            if (attrValue==null) continue;
            if (attrName.equals("")) continue;
            if (attrValue.equals("")) continue;
            attrList.add(attrName);
            attrList.add(attrValue);
        }
        return attrList;
    }
    
    public static void main(String[] args) throws Exception {
        AttributeDAO dao = new AttributeDAO();
        List l = dao.getAttributesFor("cecilie@fongen.no");
        System.out.println(l);
        
    }
}
